<!--
 * @Author: adolphus adolphus520@163.com
 * @Date: 2022-12-04 10:50:55
 * @LastEditors: 姚杰鸿
 * @LastEditTime: 2024-11-07 14:33:27
 * @Description: file content
-->
<template>
  <el-row :gutter="20" justify="center">
    <el-col :span="15">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <el-row class="row-bg" justify="space-between">
              <el-col :span="3"></el-col>
              <el-col :span="12">
                <span class="title">重设置密码</span>
              </el-col>
              <el-col :span="3"></el-col>
            </el-row>
          </div>
        </template>
        <el-collapse-transition>
          <el-form
            ref="findkeyFormRef"
            :model="form"
            :rules="rules(user)"
            v-if="stepActive == 1"
          >
            <el-form-item prop="mobile">
              <el-space :size="3">
                <el-input
                  v-model="form.mobile"
                  :prefix-icon="Phone"
                  placeholder="注册时填的手机号"
                />
                <el-link
                  type="primary"
                  :disabled="timer != 0"
                  @click.prevent="sendVerificationCode(findkeyFormRef)"
                  class="get-vf-code-btn"
                >
                  {{
                    timer === 0
                      ? "验证码"
                      : timer === 60
                        ? `发送中...`
                        : `${timer}秒后再发送`
                  }}
                </el-link>
              </el-space>
            </el-form-item>
            <el-form-item prop="verificationCode">
              <el-space :size="3">
                <el-input
                  v-model="form.verificationCode"
                  :prefix-icon="Message"
                  placeholder="输入手机短信验证码"
                  clearable
                />
                <div class="get-vf-code-btn">
                  <el-button
                    type="primary"
                    plain
                    @click="commit(findkeyFormRef)"
                  >
                    验证
                  </el-button>
                </div>
              </el-space>
            </el-form-item>
          </el-form>
        </el-collapse-transition>
        <el-collapse-transition>
          <el-form
            ref="findkeyFormRef"
            :model="user"
            :rules="rules(user)"
            v-if="stepActive == 2"
          >
            <el-form-item prop="account">
              <el-input
                v-model="user.account"
                :prefix-icon="CreditCard"
                placeholder="账户名"
              />
            </el-form-item>

            <el-form-item prop="authkey">
              <el-space direction="vertical" :size="2" class="authkey-space">
                <el-input
                  v-model="user.authkey"
                  type="password"
                  placeholder="账户密码"
                  show-password
                  :prefix-icon="Lock"
                />
                <div class="psw-lvl-progress">
                  <el-progress
                    v-if="pswLvlPer > 0"
                    :text-inside="true"
                    :percentage="pswLvlPer"
                    :color="pswLvlColors"
                    :stroke-width="20"
                  >
                    <span> {{ pswLvl }} </span>
                  </el-progress>
                </div>
              </el-space>
            </el-form-item>
            <el-row class="row-bg" justify="space-between">
              <el-col :span="6">
                <el-button type="primary" plain @click="stepActive = 1">
                  上一步
                </el-button>
              </el-col>
              <el-col :span="10"></el-col>
              <el-col :span="8">
                <el-button type="primary" plain @click="commit(findkeyFormRef)">
                  重置密码
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-collapse-transition>
        <el-collapse-transition>
          <div style="height: 204.19px" v-if="stepActive == 3">
            <el-result
              style="padding: 0px"
              icon="success"
              title="重置成功"
              sub-title="请返回登录界面尝试登录"
            >
              <template #extra>
                <el-button type="primary" @click="toSignIn"> 登录页 </el-button>
              </template>
            </el-result>
          </div>
        </el-collapse-transition>
        <el-divider content-position="left">寻求帮助 </el-divider>
        <el-row class="row-bg" justify="space-between">
          <el-col :span="6">
            <el-link type="warning">
              <router-link v-slot="{ href }" to="/login.html">
                <a :href="href">已有帐号</a>
              </router-link>
            </el-link>
          </el-col>
          <el-col :span="6"></el-col>
          <el-col :span="6">
            <el-link type="success">
              <router-link v-slot="{ href }" to="/register.html">
                <a :href="href">注册</a>
              </router-link>
            </el-link>
          </el-col>
        </el-row>
      </el-card>
    </el-col>
    <div class="div-space"></div>
    <el-col :span="24">
      <el-steps :active="stepActive" align-center>
        <el-step title="验证用户" :icon="Edit" />
        <el-step title="重置密码" :icon="Upload" />
        <el-step title="完成重置" :icon="Check" />
      </el-steps>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onDeactivated, watch } from "vue";
import {
  Lock,
  CreditCard,
  Edit,
  Upload,
  Check,
  Phone,
  Message,
} from "@element-plus/icons-vue";
import { useIntervalFn } from "@vueuse/core";
import {
  UserVfCodeApi,
  UserCheckVfCodeApi,
  UserResetAutkeyApi,
} from "@/apis/home";
import type { FormInstance, FormRules } from "element-plus";
import { phone, verificationCode as vfCode } from "@/lib/formCheck";
import { validateUserPassword } from "@/lib/inputCheck";
import { level } from "@/lib/passwordCheck";
import { useRouter } from "vue-router";

// do not use same name with ref
const form = reactive({
    mobile: "",
    verificationCode: "",
  }),
  user = reactive({
    account: "",
    authkey: "",
    resetToken: "",
  }),
  $router = useRouter(),
  findkeyFormRef = ref<FormInstance>(),
  rules = (d: any): FormRules => {
    return {
      mobile: phone,
      verificationCode: vfCode,
      account: [{ required: true, message: "账户名信息必填", trigger: "blur" }],
      authkey: [
        {
          required: true,
          validator: (rule, value, cb) => {
            validateUserPassword(rule, d.account, value, cb);
          },
          trigger: "blur",
        },
      ],
    };
  },
  stepActive = ref(1),
  timer = ref(0),
  pswLvlPer = ref(0),
  pswLvlColors = [
    { color: "black", percentage: 20 },
    { color: "red", percentage: 40 },
    { color: "orange", percentage: 60 },
    { color: "green", percentage: 80 },
    { color: "blue", percentage: 100 },
  ],
  pswLvl = ref(""),
  { pause, resume } = useIntervalFn(
    () => {
      //每次定时任务 控制时间递减
      if (timer.value <= 0) {
        // 停止递减：停止定时器
        pause();
        localStorage.removeItem("zcStartTimeLogin");
      } else {
        timer.value -= 1;
      }
    },
    1000,
    {
      // 首次是否自动启动定时任务：true（默认值，自动启动），false，不需要自动启动
      immediate: false,
      // 是否延时执行定时任务（false(默认值)，不延时；true表示延时）
      immediateCallback: false,
    }
  ),
  sendVerificationCode = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validateField("mobile", (valid) => {
      if (valid) {
        timer.value = 60;
        UserVfCodeApi(form.mobile)
          .then((res) => {
            console.log(res.status, res.data.code);
            if (200 == res.status && 200 == res.data.code) {
              //开启定时效果
              // 重启定时器
              resume();
              localStorage.setItem(
                "zcStartTimeLogin",
                String(new Date().getTime())
              );
            } else {
              timer.value = 0;
              ElMessage.error(res.data.msg);
            }
          })
          .catch((err) => {
            timer.value = 0;
            ElMessage.error("发送验证码出现错误！");
          });
      }
    });
  },
  commit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        if (stepActive.value === 1) {
          UserCheckVfCodeApi(form.mobile, form.verificationCode)
            .then((res) => {
              if (200 == res.status) {
                user.resetToken = res.data.data.resetToken;
                stepActive.value = 2;
              } else {
                ElMessage.error(res.data.msg);
              }
            })
            .catch((err) => {
              console.log(err);
              ElMessage.error(err.response.data.msg);
            });
        }
        if (stepActive.value === 2) {
          UserResetAutkeyApi(user)
            .then((res) => {
              if (200 == res.status) {
                stepActive.value = 3;
              } else {
                ElMessage.error(res.data.msg);
              }
            })
            .catch((err) => {
              console.log(err);
              ElMessage.error(err.response.data.msg);
            });
        }
      }
    });
  },
  toSignIn = () => {
    $router.push({ name: "Login", state: { account: user.account } });
  };

onMounted(() => {
  let startTime = Number(localStorage.getItem("zcStartTimeLogin"));
  let nowTime = new Date().getTime();
  if (startTime) {
    let surplus = 60 - parseInt(String((nowTime - startTime) / 1000), 10);
    timer.value = surplus <= 0 ? 0 : surplus;
    resume();
  }
});

onDeactivated(() => {
  stepActive.value = 1;
  form.mobile = "";
  form.verificationCode = "";
  user.account = "";
  user.authkey = "";
  user.resetToken = "";
});

// 监听注册页面的新密码变化状态，来改变密码强弱显示
watch(
  () => user.authkey,
  (newVal) => {
    if (newVal && newVal != "") {
      const res: string = level(newVal);
      if (res == "非常弱") {
        pswLvlPer.value = 20;
        pswLvl.value = "非常弱";
      } else if (res == "弱") {
        pswLvlPer.value = 40;
        pswLvl.value = "弱";
      } else if (res == "一般") {
        pswLvlPer.value = 60;
        pswLvl.value = "一般";
      } else if (res == "强") {
        pswLvlPer.value = 80;
        pswLvl.value = "强";
      } else if (res == "非常强") {
        pswLvlPer.value = 100;
        pswLvl.value = "非常强";
      }
    } else {
      pswLvlPer.value = 0;
      pswLvl.value = "";
    }
  }
);
</script>

<style lang="scss" scoped>
.title {
  font-size: x-large;
  font-weight: 500;
}
.box-card {
  width: 325px;
}
.get-vf-code-btn {
  width: 100px;
}
.div-space {
  width: 100%;
  height: 15px;
}
.findkey-result {
  padding: 0px;
}
.psw-lvl-progress {
  width: 200px;
  min-width: 100px;
  max-width: 600px;
}
</style>

<style lang="scss">
.authkey-space {
  width: 100%;
}
.authkey-space .el-space__item {
  width: 100%;
}
</style>
